import Vue from 'vue'
import Vuex from 'vuex'
// 导入持久化存储vuex包
import createPersistedState from 'vuex-persistedstate'
// 导入axios
import axios from 'axios'
Vue.use(Vuex)

export default new Vuex.Store({
  // 2. 配置为 vuex 的插件
  plugins: [createPersistedState()],
  state: {
    // 默认去localStorage中取
    // token: localStorage.getItem('token') || ''
    token: '',
    userInfo: {}
  },
  mutations: {
    // 不能直接操纵data中数据要借助mutations中的函数来改变data中数值
    updateToken (state, token) {
      state.token = token
      // 让插件自己完成存储
      // localStorage.setItem('token', token)
    },
    updateUserInfo (state, userInfo) {
      state.userInfo = userInfo
    }
  },
  actions: {
    async getUserInfo (context) {
      // console.log(context.state.token)
      const { data: res } = await axios.get('/my/userinfo'
      // , {headers: { Authorization: context.state.token }}
      )
      // console.log(res)
      if (res.code === 0) {
        context.commit('updateUserInfo', res.data)
      }
    }
  },
  modules: {
  }
})
